package com.gaogzhen.service;

import com.gaogzhen.dao.AccountDao;
import com.gaogzhen.domain.Account;
import com.gaogzhen.utils.JdbcUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author Administrator
 * @date 2022-12-05 10:12
 */
public class AccountService {
    AccountDao dao = new AccountDao();

    /**
     * 转账
     * @param out   转出账户
     * @param in    转入账户
     * @param money 转账金额
     * @return      是否成功
     */
    public boolean transfer(Account out, Account in, BigDecimal money) {
        Connection conn = null;
        try {
            // 1 开启事务
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);
            dao.out(out, money);
            int i = 1/0;
            dao.in(in, money);
            // 2 成功提交
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            // 3 异常回滚
            JdbcUtils.rollback(conn);
            return false;
        }
        return true;
    }

    public Account getById(int id) {
        try {
            Account account = dao.getById(id);
//            dao.close();
            return account;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void close() {
        dao.close();
    }
}
